import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.gingko.duominuo.R
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.databinding.FragmentTaskLinkBottomBinding
import com.gingko.duominuo.ui.fragment.WebViewFragment
import com.gingko.duominuo.ui.fragment.X5KernelFragment
import com.gingko.duominuo.utils.dp2px
import com.gingko.duominuo.utils.screenHeight
import com.gingko.duominuo.utils.screenWidth
import com.gingko.duominuo.utils.singleClick
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.runBlocking

class TaskLinkBottomFragment : DialogFragment() {
    private val mViewBinding: FragmentTaskLinkBottomBinding by lazy {
        FragmentTaskLinkBottomBinding.inflate(
            layoutInflater
        )
    }
    private lateinit var link: String;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.dialog_bottom_style)
        link = arguments?.getString(ARG_LINK) ?: ""
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.apply {
            setWindowAnimations(R.style.bottom_dialog_anim)
            attributes.gravity = Gravity.BOTTOM
            attributes = attributes?.apply {
                width = screenWidth
            }

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mViewBinding.ivClose.singleClick {
            dismiss()
        }

        val isUseX5Kernel = runBlocking {
            DataStoreHelper.isUseX5Kernel()
        }
        val fragment = if (isUseX5Kernel) {
            X5KernelFragment.newInstance(link)
        } else {
            WebViewFragment.newInstance(link)
        }
        childFragmentManager.beginTransaction().replace(R.id.fl_container, fragment).commit()
    }

    companion object {
        private const val ARG_LINK = "link"

        @JvmStatic
        fun newInstance(link: String) =
            TaskLinkBottomFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_LINK, link)
                }
            }
    }

}